<template>
  <div
    :class="[prefixCls + '-alpha']"
    tabindex="0"
    @click="$el.focus()"
    @keydown.esc="handleEscape"
    @keydown.left="handleLeft"
    @keydown.right="handleRight"
    @keydown.up="handleUp"
    @keydown.down="handleDown"
  >
    <div :class="[prefixCls + '-alpha-checkboard-wrap']">
      <div :class="[prefixCls + '-alpha-checkerboard']"></div>
    </div>
    <div
      :style="gradientStyle"
      :class="[prefixCls + '-alpha-gradient']"></div>
    <div
      ref="container"
      :class="[prefixCls + '-alpha-container']"
      @mousedown="handleMouseDown"
      @touchmove="handleChange"
      @touchstart="handleChange">
      <div
        :style="{top: 0, left: `${value.a * 100}%`}"
        :class="[prefixCls + '-alpha-pointer']">
        <div :class="[prefixCls + '-alpha-picker']"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {inject,ref,watch, computed} from "vue"
import {clamp,toRGBAString,getTouches} from "../utils"
import {isClient} from "../../../utils/index"
import {useHas} from "./utils"
defineOptions({
  name: 'Alpha'
})

const props=defineProps({
  focused: {
    type: Boolean,
    default: false,
  },
  value: {
    type: Object,
    default: undefined,
  }
})

const emits=defineEmits(['change'])
const ColorPickerInstance=inject('ColorPickerInstance')
// const handleEscape=()=>{
//   ColorPickerInstance.handleOnEscapeKeydown()
// }
const normalStep = 1;
const jumpStep = 10;
let left=ref(-normalStep)
let right=ref(normalStep)
let up=ref(jumpStep)
let down=ref(-jumpStep)
let powerKey=ref('shiftKey')
// let percent=ref(clamp(props.value.hsl.h * 100 / 360, 0, 100))
let container=ref();

const prefixCls=ref('haloe-color-picker')

const gradientStyle=computed(()=>{
  const {r,g,b}=props.value.rgba;
  const start = toRGBAString({r, g, b, a: 0});
  const finish = toRGBAString({r, g, b, a: 1});

  return { background: `linear-gradient(to right, ${start} 0%, ${finish} 100%)` };
})

const change= (newAlpha)=> {
  const { h, s, l } = props.value.hsl;
  const { a } = props.value;
  // console.log('a',props.value,a)
  if (a !== newAlpha) {
    emits('change', {h, s, l, a: newAlpha, source: 'rgba'});
  }
}

const handleSlide= (e, direction)=> {
  e.preventDefault();
  e.stopPropagation();

  change(clamp(e[powerKey.value] ? direction : Math.round(props.value.hsl.a * 100 + direction) / 100, 0, 1));
}

const getLeft= (e)=> {
  if (!isClient) return;
  // const {container} = this.$refs;
  const xOffset = container.value.getBoundingClientRect().left + window.pageXOffset;
  const pageX = e.pageX || getTouches(e, 'PageX');

  return pageX - xOffset;
}

const handleChange= (e)=> {
  e.preventDefault();
  e.stopPropagation();

  const left =getLeft(e);

  if (left < 0) {
    change(0);
    return;
  }

  const { clientWidth } = container.value;

  if (left > clientWidth) {
    change(1);
    return;
  }
  // console.log('left',left,clientWidth)
  change(Math.round(left * 100 / clientWidth) / 100);
}


const {handleLeft,handleRight,handleUp,handleDown,handleMouseDown,handleEscape}=useHas({left:left.value,right:right.value,up:up.value,down:down.value},handleChange,handleSlide,ColorPickerInstance)

// const handleLeft=(e)=> {
//   handleSlide(e, left.value, 'left');
// }
// const handleRight= (e)=> {
//   handleSlide(e, right.value, 'right');
// }
// const handleUp =(e)=> {
//   handleSlide(e, up.value, 'up');
// }
// const handleDown= (e)=> {
//   handleSlide(e, down.value, 'down');
// }

// const handleMouseUp= ()=> {
//   unbindEventListeners();
// }

// const handleMouseDown= (e)=> {
//   ColorPickerInstance.handleOnDragging(true);
//   handleChange(e, true);
//   // window.addEventListener('mousemove', this.handleChange, false);
//   // window.addEventListener('mouseup', this.handleMouseUp, false);
//   on(window, 'mousemove', handleChange);
//   on(window, 'mouseup', handleMouseUp);
// }

// const unbindEventListeners= ()=> {
//   // window.removeEventListener('mousemove', this.handleChange);
//   // window.removeEventListener('mouseup', this.handleMouseUp);
//   off(window, 'mousemove', handleChange);
//   off(window, 'mouseup', handleMouseUp);
//   // This timeout is required so that the click handler for click-outside
//   // has the chance to run before the mouseup removes the dragging flag.
//   setTimeout(() => ColorPickerInstance.handleOnDragging(false), 1);
// }



// onBeforeUnmount(() => {
//   unbindEventListeners();
// })

/*

    created () {
        if (this.focused) {
            setTimeout(() => this.$el.focus(), 1);
        }
    },
*/ 

</script>

<style>

</style>